<?php
namespace app\common\service\message\order;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\model\Setting as SettingModel;
use app\common\service\message\Basics;

/**
 *  用户分红退款通知
 * Class Abonus
 * @package app\common\service\message\order
 */
class Abonus extends Basics
{

    /**
     * 参数列表
     * @var array
     */
    protected $param = [
        'order' => [],         // 拼单详情
        'user_id'=>'',         //会员id
        'money' =>'',          //我的收益
        'order_type' => OrderTypeEnum::MASTER,
    ];

    /**
     * 订单页面链接
     * @var array
     */
    private $pageUrl = [
        //普通订单
        OrderTypeEnum::MASTER => 'pages/order/detail',
        //砍价订单
        OrderTypeEnum::SHARING => 'pages/sharing/order/detail/detail',
        //当面付订单
        OrderTypeEnum::FACEPAY => 'pages/face/index',
        //储值订单
        OrderTypeEnum::VIPCARD => 'pages/vip/vip',
    ];

    /**
     * 发送消息通知
     * @param array $param
     * @return mixed|void
     * @throws \think\Exception
     */
    public function send($param)
    {
        // 记录参数
        $this->param = $param;
        // 微信订阅消息通知用户
        $this->onSendWxSubMsg();
    }

    /**
     * 微信订阅消息通知用户
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    private function onSendWxSubMsg()
    {
        // 拼单详情
        $orderInfo = $this->param['order'];
        $orderType = $this->param['order_type'];
        $wxappId = $orderInfo['wxapp_id'];
        $user=$this->getParentUser($this->param['user_id']);
        $money=$this->param['money'];
        // 获取订阅消息配置
        $template = SettingModel::getItem('submsg', $wxappId)['order']['abonus'];
        if (empty($template['template_id'])) {
            return false;
        }
        // 发送订阅消息
        return $this->sendWxSubMsg($wxappId, [
            'touser' => $user['open_id'],
            'template_id' => $template['template_id'],
            'page' => "{$this->pageUrl[$orderType]}?order_id={$orderInfo['order_id']}",
            'data' => [
                // 会员名
                $template['keywords'][0] => ['value' =>$user['nickName']],
                // 订单金额
                $template['keywords'][1] => ['value' => $orderInfo['pay_price']],
                // 我的收益
                $template['keywords'][2] => ['value' => $money],
                // 下单时间
                $template['keywords'][3] => ['value' => format_time($orderInfo['pay_time'])],
            ]
        ]);
    }
    /**
     *  获取上级用户信息
     * @param $userId
     * @return array|bool|false|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getParentUser($userId){
        return db('user')->where('user_id',$userId)->find();
    }

}